package TXPathFinder;

import java.io.*;
import java.net.*;

/**
*       \class	SocketClient
*	\brief	Gère la connection entre le programme Java et le programme C++ à l'aide de socket
**/
public class SocketClient {
	
    PrintWriter _writer = null;
    BufferedReader _reader = null;
    public boolean _connected = false;

    /**
    *	\brief	Constructeur
    *   \param IPAdress Adresse pour se connecter au serveur C++
    **/
    public SocketClient(String IPAddress)
    {
        // Connexion
        Socket conn = null;
        while (_connected == false)
        {
            try
            {
                conn = new Socket("localhost", 8080 );
                conn.setTcpNoDelay(true);
                _connected = true;
            }
            catch (Exception e1)
            {
                try
                {
                    // On attend 100ms avant de retenter une connection
                    Thread.sleep(100);
                }
                catch (Exception e2)
                {
                    e2.printStackTrace();
                }
            }
        }

        try
        {
            _writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())),true);
            _reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        }
        catch ( Exception e )
        {
            _connected = false;
            e.printStackTrace();
        }
    }

    /**
    *	\brief	Ecrit une requete pour le serveur
    *   \param question Requete pour le serveur
    **/
    protected void write(String question)
    {
        _writer.println(question);
    }

    /**
    *	\brief	Lit les réponses du serveur
    *   \return Le xml résultat de la reponse
    **/
    public String read()
    {
        try
        {
            String xml = _reader.readLine();
            if (xml == null) xml = "<Error/>";
            return xml;
        }
        catch (Exception e)
        {
            _connected = false;
            e.printStackTrace();
            return "<Error/>";
        }
    }
}
